package com.yunxin.core.infra.common.order;


import cn.hutool.core.util.ObjUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 订单调度
 */
@Component
@Slf4j
public class OrderScheduling {


    private Integer num;

    private Long second;

   private final Semaphore semaphore;


    public OrderScheduling(@Value("${allocation.order.semaphore-num:3}") Integer num,@Value("${allocation.order.semaphore-second:10}") Long second) {
        log.info("实例化订单调度器-最大信号量为：{}" + num);
        this.semaphore = new Semaphore(num);
        this.num = num;
        this.second = second;
    }


    /**
     * 尝试获取许可证
     * @param timeout 秒
     * @return 失败false
     */
    public boolean tryAcquire(Long timeout) {
        timeout = ObjUtil.defaultIfNull(timeout, this.second);
        try {
            return semaphore.tryAcquire(1,timeout, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 尝试获取许可证
     * @return 成功true
     */
    public boolean tryAcquire() {
        return tryAcquire(this.second);
    }


    public void release(){
        semaphore.release();
    }

}
